import Knex from "~/src/library/mysql";
import moment from "moment";
import _ from "lodash";
import DATE_FORMAT from "~/src/constants/date_format";

const TableNameDateFormat = "YYYYMM";
const VisitAtHourDateFormat = DATE_FORMAT.DATABASE_BY_HOUR;
const BASE_TABLE_NAME = "t_r_page_view";
const TABLE_COLUMN = [
  `id`,
  `project_id`,
  `total_count`,
  `url`,
  `dt`,
  `dl`,
  `dr`,
  `dpr`,
  `de`,
  `city_distribute_id`,
  `count_type`,
  `count_at_time`,
  `create_time`,
  `update_time`,
];

/**
 * 获取表名
 * @param {number} projectId 项目id
 * @param {number} createTimeAt 创建时间, 时间戳
 * @return {String}
 */
function getTableName(projectId, createTimeAt) {
  let dateYm = moment.unix(createTimeAt).format(TableNameDateFormat);
  return `${BASE_TABLE_NAME}_${projectId}`; //_${dateYm}
}

/**
 * 自动创建&更新uv记录(不更新pv, pv无意义)
 * @param {number} projectId
 * @param {string} uuid
 * @param {number} count_at_time
 * @param {string} country
 * @param {string} province
 * @param {string} city
 * @return {boolean}
 */
async function replacePvRecord(
  projectId,
  uid,
  url,
  dt,
  dl,
  dr,
  dpr,
  de,
  total_count,
  city_distribute_id,
  countType,
  countAt
) {
  let tableName = getTableName(projectId, countAt);
  let dateFormat = DATE_FORMAT.DATABASE_BY_UNIT[countType];

  let countAtTime = moment.unix(countAt).format(dateFormat);
  let updateAt = moment().unix();
  // 返回值是一个列表
  // let oldRecordList = await Knex.select([`id`])
  //   .from(tableName)
  //   // .where("uid", "=", uid)
  //   .catch(() => {
  //     return [];
  //   });
  // // 利用get方法, 不存在直接返回0, 没毛病
  // let id = _.get(oldRecordList, [0, "id"], 0);
  let data = {
    uid,
    url,
    dt,
    dl,
    dr,
    dpr,
    de,
    total_count,
    city_distribute_id,
    count_type: countType,
    count_at_time: countAtTime,
    update_time: updateAt,
  };

  // let isSuccess = false;
  // if (id > 0) {
  //   let affectRows = await Knex(tableName).update(data).where(`id`, "=", id);
  //   isSuccess = affectRows > 0;
  // } else {
    data["create_time"] = updateAt;
    console.log(tableName, data);
    let insertResult = await Knex.insert(data, ["id"])
      .into(tableName)
      .catch(e => {
        return [];
      });
    let insertId = _.get(insertResult, [0], 0);
  //   isSuccess = insertId > 0;
  // }
  return insertId;
}

/**
 * 获取一段时间范围内的uv数
 * @param {*} projectId
 * @param {*} startAt
 * @param {*} endAt
 * @returns {Number}
 */
async function getPVInRange(projectId, startAt, endAt) {
  let startAtMoment = moment.unix(startAt).format(DATE_FORMAT.DATABASE_BY_HOUR)
  let finishAtMoment = moment.unix(endAt).format(DATE_FORMAT.DATABASE_BY_HOUR)
  let tableName = getTableName(projectId, startAt)
  let rawRecord = await Knex
    .from(tableName)
    .sum('total_count as total')
    .where('count_type', '=', DATE_FORMAT.UNIT.HOUR)
    .andWhere('count_at_time', '>=', startAtMoment)
    .where('count_at_time', '<', finishAtMoment)
    .catch(e => {
      return 0
    })
  // let startAtMoment =moment.unix(startAt).startOf(DATE_FORMAT.DATABASE_BY_HOUR)
  // let tableName = getTableName(projectId, startAt);
  // let countAtTimeList = [];

  // // 获取所有可能的countAtTime
  // for (
  //   let countStartAtMoment = startAtMoment.clone();
  //   countStartAtMoment.unix() < endAt;
  //   countStartAtMoment = countStartAtMoment
  //     .clone()
  //     .add(1, DATE_FORMAT.UNIT.HOUR)
  // ) {

  //   let formatCountAtTime = moment.unix(countStartAtMoment).format(DATE_FORMAT.UNIT.HOUR);
  //   console.log(formatCountAtTime)
  //   countAtTimeList.push(formatCountAtTime);
  // }
  // let rawRecord = await Knex.from(tableName)
  //   // .sum("total_count as total")
  //   .where("count_type", "=", DATE_FORMAT.UNIT.HOUR)
  //   .whereIn("count_at_time", countAtTimeList)
  //   .catch(e => {
  //     return 0;
  //   });
  // console.log( countAtTimeList);
  let totalPV = _.get(rawRecord, [0, "total"], 0);
  return totalPV;
}

export default {
  replacePvRecord,
  getPVInRange,
  getTableName,
};
